package com.meiqiongproperty.yiguanjia.fragment.home.h5;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.meiqiongproperty.yiguanjia.R;
import com.meiqiongproperty.yiguanjia.activity.BaseFragmentActivity;
import com.meiqiongproperty.yiguanjia.utils.LogUtil;
import com.meiqiongproperty.yiguanjia.utils.StringUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;

/**
 * @version V1.0
 * @packge com.meiqiongproperty.yiguanjia.fragment.home.h5
 * @User ChenJing
 * @Date 2017/6/11
 */

public class H5UserActivity extends BaseFragmentActivity implements
        ExcuteDialogFragmentCallBack {
    private FrameLayout btn_left;
    private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");

    public static String mRedirectUrl;
    public static String Right_t;
    public static boolean isshow, title_color, title_show, finance_case;
    /**
     * KEY DIALOG:
     */
    private static final String KEY_NET_UNCONNECT_DIALOG = "H5UserActivity_NetWork_Unconnect";
    /**
     * URL:传值的KEY
     */
    public static final String URL = "url";
    public static final String TITLE = "title";
    public static final String RIGHT_TEXT = "right_text";
    /**
     * mPageTitle:页面标题
     */
    private String mPageTitle = "";
    private ProgressBar mProgressBar;
    private TextView right, message;
    private WebView mWebView;
    private H5UserActivity activity;
    private LinearLayout ll_h5_head;
    // private QedBaseDialogFragment dialog;
    private String url;
    private String path = " ";
    LinearLayout root_webview;
    View view;
    private View.OnClickListener mClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.common_titleview_btn_left:// 返回
                        finishCurrentActivity();
                        break;
            }
        }
    };


    @Override
    public void onPositiveBtnClick(String tag) {

    }

    @Override
    public void onNegtiveBtnClick(String tag) {
        if (TextUtils.isEmpty(tag)) {
            return;
        }
        if (tag.equalsIgnoreCase(KEY_NET_UNCONNECT_DIALOG)) {
            finishCurrentActivity();
        }
    }

    @SuppressLint({"SetJavaScriptEnabled", "ResourceAsColor"})
    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.user_introduce);
        ChangeStatusBar();

        getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
        /*
         * getWindow().setSoftInputMode(WindowManager.LayoutParams.
		 * SOFT_INPUT_ADJUST_RESIZE |
		 * WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		 */
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenW = dm.widthPixels;
        int screenH = dm.heightPixels;
        if (getIntent() != null) {
            String url = getIntent().getStringExtra(URL);
            String title = getIntent().getStringExtra(TITLE);
            String right_text = getIntent().getStringExtra(RIGHT_TEXT);
            if (!StringUtils.emptyOrNull(url)) {
                mRedirectUrl = url;
            }
            if (!StringUtils.emptyOrNull(right_text)) {
                Right_t = right_text;
            }
            if (!StringUtils.emptyOrNull(title)) {
                mPageTitle = title;
            } else {
                if (null != getResources()) {
                    mPageTitle = getResources().getString(R.string.app_name);
                }
            }
        }

        root_webview = (LinearLayout) findViewById(R.id.root_webview);
        message = (TextView) findViewById(R.id.message);

        root_webview.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        Rect r = new Rect();
                        root_webview.getWindowVisibleDisplayFrame(r);

                        int screenHeight = root_webview.getRootView()
                                .getHeight();
                        // int KeyboardHeigth = screenHeight - (r.bottom - r.top);
                        int KeyboardHeigth = screenHeight - r.bottom;
                        // CommonUtil.showToast("height-------------->"+KeyboardHeigth);
                        FrameLayout.LayoutParams linearParams = (FrameLayout.LayoutParams) root_webview
                                .getLayoutParams(); // 取控件mGrid当前的布局参数
                        linearParams.height = screenHeight - KeyboardHeigth;// 当控件的高强制设成75象素
                        root_webview.setLayoutParams(linearParams); // 使设置好的布局参数应用到控件mGrid2
                    }

                });

        view = (View) findViewById(R.id.h5_title);
        view.setVisibility(View.VISIBLE);
        view.setBackgroundResource(R.color.app_basic_color);
        ((TextView) view.findViewById(R.id.common_titleview_text))
                .setText(mPageTitle);
        btn_left = (FrameLayout) view
                .findViewById(R.id.common_titleview_btn_left);
        btn_left.setOnClickListener(mClickListener);
        right = (TextView) view.findViewById(R.id.common_right_text);


        if (isshow) {
            right.setText(Right_t);
            right.setVisibility(View.VISIBLE);
            right.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                }
            });
        } else {
            right.setVisibility(View.GONE);
        }

        mProgressBar = (ProgressBar) findViewById(R.id.progressbar);
        mProgressBar.setVisibility(View.VISIBLE);

        mWebView = (WebView) findViewById(R.id.user_intro_webview);
        mWebView.addJavascriptInterface(new AndroidForJsH5User(
                H5UserActivity.this), "JavaScriptInterface");
        mWebView.setVerticalScrollBarEnabled(false);
        mWebView.setHorizontalScrollBarEnabled(false);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setWebViewClient(getWebClient());
        mWebView.setWebChromeClient(new MyWebView());
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
        LogUtil.d("mRedirectUrl--------->" + mRedirectUrl);

//        WebSettings webSetting = mWebView.getSettings();
//        webSetting.setJavaScriptEnabled(true);
//        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
//        webSetting.setAllowFileAccess(true);
//        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
//        webSetting.setSupportZoom(true);
//        webSetting.setBuiltInZoomControls(true);
//        webSetting.setUseWideViewPort(true);
//        webSetting.setSupportMultipleWindows(true);
//        webSetting.setLoadWithOverviewMode(true);
//        webSetting.setAppCacheEnabled(true);
//        webSetting.setDatabaseEnabled(true);
//        webSetting.setDomStorageEnabled(true);
//        webSetting.setGeolocationEnabled(true);
//        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
//        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
//        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
//        webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
//        webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.loadUrl(mRedirectUrl);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((KeyEvent.KEYCODE_BACK == keyCode) && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        if ((keyCode == 1001) && mWebView.canGoBack()) {
//			toH5(URL, "投资成功");
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private WebViewClient getWebClient() {
        return new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view,
                                                    final String url) {
                LogUtil.d("H5UserActivityshouldOverrideUrlLoadingurl---------------->"
                        + url);
                Uri uri = Uri.parse(Uri.decode(url));
                // 这边做一些匹配工作
                boolean isHandle = false;
                if (uri != null && uri.getHost() != null
                        && !uri.getHost().contains("51qed.com")
                        && !uri.getHost().contains("sina")
                        && !uri.getHost().contains("mcashier")) {
                    isHandle = true;
                } else if (uri.toString().contains("@")) {
                    // findViewById(R.id.h5usercontainer_titleview).setVisibility(
                    // View.VISIBLE);
                } else {
                    // findViewById(R.id.h5usercontainer_titleview).setVisibility(
                    // View.GONE);
                    isHandle = shouldOverrideUrlLoadingForSubClass(url);
                }

                if (isHandle) {
                    return true;
                } else {
                    return super.shouldOverrideUrlLoading(view, url);
                }
            }

            @Override
            public void onReceivedSslError(WebView view,
                                           SslErrorHandler handler, SslError error) {
                super.onReceivedSslError(view, handler, error);
                }



            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                LogUtil.d("H5UserActivityonPageStarted--------------");
                if (url != null && url.contains("yintong.com.cn")) {
                    // findViewById(R.id.h5usercontainer_titleview).setVisibility(
                    // View.GONE);
                    // LogUtil.d("yintong.com.cn");
                } else {
                    // findViewById(R.id.h5usercontainer_titleview).setVisibility(
                    // View.VISIBLE);
                }
                // dialog = QedDialogManager.showProcessDialog(
                // H5UserActivity.this, BusinessController
                // .getAttribute(CacheKeyEnum.isShowDialog),
                // "login_loading", true, false, false);
            }

            @Override
            public void onReceivedError(WebView view, final int errorCode,
                                        final String description, final String failingUrl) {
                LogUtil.d("onReceivedError--------------");

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                LogUtil.d("onPageFinished--------------");
            }
        };
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    public boolean shouldOverrideUrlLoadingForSubClass(String url) {
        // TODO:
        return false;
    }


    private class MyWebView extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            mProgressBar.setProgress(newProgress);
            if (newProgress == 100) {
                mProgressBar.setVisibility(View.GONE);
            }
            super.onProgressChanged(view, newProgress);
        }
    }

}